<?php
/**
 * CreateUser: zlh
 * CreateTime: 2022/4/24 13:57
 * Remark:
 */

namespace App\Service\Auth;

use App\Consts\ResponseConsts\ResponseStatusConsts;
use App\Func\ResponseFunc;
use App\Models\Auth\AuthRoleModel;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Support\Facades\DB;
use Mockery\Exception;

class AuthRoleService
{
    private AuthRoleModel $_authRoleModel;

    public function __construct()
    {
        $this->_authRoleModel = new AuthRoleModel();
    }

    public function getRoleAuthInfo($roleId){
        return $this->_authRoleModel->getRoleAuthInfo($roleId);
    }

    public function addRoleAuthByRole($auths,$roleId){
        $insertValue = "";
        foreach($auths as $key => $value){
            $insertValue.= "($roleId,".$value['auth_id'].",".$value['auth_value']."),";
        }
        // 去掉最后一位
        $insertValue = substr($insertValue,0,strlen($insertValue)-1);
        // 删除上一次角色绑定的权限
        try {
            DB::beginTransaction();
            $this->_authRoleModel->deleteRoleAuthByRole($roleId);
            $res = $this->_authRoleModel->saveRoleAuthByRole($insertValue);
            if(!$res){
                throw new HttpResponseException(ResponseFunc::returnJson(
                    'error',
                    null,
                    '绑定角色权限错误',
                    ResponseStatusConsts::OK_200_RESPONSE_STATUS,
                ));
            }
            DB::commit();
            return $res;
        }catch (Exception $exception){
            DB::rollBack();
            throw new HttpResponseException(ResponseFunc::returnJson(
                'error',
                null,
                $exception->getMessage(),
                ResponseStatusConsts::OK_200_RESPONSE_STATUS,
            ));
        }


    }




}